<template>
    <div class="city-search">
        <div class="city-search-wrap">
            <input type="text" placeholder="输入城市名或者拼音" v-model="keywords">
        </div>
        <!--是否显示取决于搜索关键词匹配的数组是否有元素-->
        <template v-if="list.length">
            <div class="search-list-wrap">
                <ul class="search-list">
                    <li v-for="item of list" :key="item.id">{{item.name}}</li>
                </ul>
            </div>
        </template>
    </div>
</template>

<script>
  export default {
    name: 'CitySearch',
    data () {
      return {
        keywords: '', // 搜索关键词
        list: [], // 根据关键词匹配到的
      }
    },
    props: {
      cities: Object,
    },
    watch: {
      // 监听keywords的变化
      keywords () {
        this.list = [] // 每一次keywords发生变化都=将上一次的关键词结果数组清空
        if (this.keywords.trim()) {
          let arr = this.cityListComputed
          arr.map(item => {
            // 汉子 和 拼音模糊搜索
            if (item.name.includes(this.keywords) || item.spell.startsWith(this.keywords)) {
              this.list.push(item)
            }
          })
        } else {
          // 如果没有匹配到那么将匹配结果的数组变为空数组让 搜索到的列表隐藏
          this.list = []
        }
      },
    },
    mounted () {
      
    },
    computed: {
      cityListComputed () {
        // 计算属性优化性能： 将数组对象合并为为一个数组
        let a = Object.values(this.cities)
        let arr = []
        a.map(item => {
          arr.push(...item)
        })
        return arr
      },
    },
  }
</script>

<style scoped lang="stylus">
    @import "../assets/varibles.styl"
    
    .city-search {
        .city-search-wrap {
            background-color: $bgcolor;
            box-sizing: border-box;
            padding: 0.15rem;
            input {
                width: 100%;
                text-align: center;
                border-radius: 0.1rem;
                height: 0.7rem;
            }
        }
        .search-list-wrap {
            position: relative
            width: 100%;
            .search-list {
                background-color: #fff
                width: 100%;
                position: absolute;
                top: 0;
                z-index 5;
                min-height: 85vh;
                li {
                    border-bottom: 1px solid #ccc;
                    line-height 0.8rem;
                    padding-left: 0.2rem;
                }
            }
        }
        
    }
</style>